/*******************************************************************************
 * Copyright (c) 2010, 2030 www.itlaobing.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *******************************************************************************/
package cn.itlaobing.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itlaobing.web.annotation.RequestMapping;

/** 
 * ClassName: BaseServlet <br/> 
 * Function: TODO 功能描述 <br/> 
 * date: 2017年10月31日 下午9:23:57 <br/> 
 * 
 * @author lhb 
 * @version  
 * @since JDK 1.8 
 */
public class BaseServlet extends HttpServlet{
	//保存url和method之间的映射关系
	private Map<String,Method> requestMappings=new HashMap<>();
	/* (non-Javadoc)
	 * @see javax.servlet.GenericServlet#init()
	 */
	@Override
	public void init(ServletConfig Config) throws ServletException {
		//得到当前servlet类的class对象
		Class classServlet=this.getClass();
		//取得WebServlet 对象获取基础的url
		WebServlet webServlet=(WebServlet)classServlet.getDeclaredAnnotation(WebServlet.class);
		String baseUrl=webServlet.value()[0];
		//反射取得所有方法
		Method[] methods=classServlet.getDeclaredMethods();
		for (Method method : methods) {
			//查看方法上是否标示了@RequestMapping
			if(method.isAnnotationPresent(RequestMapping.class)) {
				RequestMapping requestMapping=method.getAnnotation(RequestMapping.class);
				//获取URL
				String url=requestMapping.value();
				if(!url.startsWith("/")) {
					url="/"+url;
				}
				String fullUrl=baseUrl.replace("/*","")+url;
				//保存到Map上
				requestMappings.put(fullUrl,method);
			}
		}
		System.out.println(requestMappings);
	}
	/* (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#service(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String requestUrl=req.getRequestURI();
		Method method=requestMappings.get(requestUrl);
		if(method==null) {
			resp.sendError(404,"error");
			return;
		}
		try {
			method.invoke(this,req,resp);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
